﻿using System;
using System.Collections.Generic;
using System.IO;

namespace DigitalQuran {

    /// <summary>
    /// User Bookmarks
    /// </summary>
    public class Bookmark {

        /// <summary>
        /// Gets the selction covered saved in bookmark
        /// </summary>
        public Selection Selection { get; private set; }

        /// <summary>
        /// Gets the associated Note
        /// </summary>
        public string Note { get; private set; }

        /// <summary>
        /// Gets the <see cref="System.DateTime"/> on which bookmark was created;
        /// </summary>
        public DateTime CreatedOn { get; private set; }

        /// <summary>
        /// Gets the <see cref="System.DateTime"/> on which bookmark was last modified
        /// </summary>
        public DateTime LastModifiedOn { get; private set; }

        #region IO
        /* Item Sequence in Bookmark Stream
         *  - Note (String)
         *  - CreatedOn (Int64)
         *  - ModifiedOn (Int64)
         *  - Selection.Scope (Byte)
         *  - Selection.Indexes.Count (Int32)
         *  (LOOP)
         *      - Index (Int32)
         */

        internal static Bookmark LoadFromStream(BinaryReader reader) {
            var b = new Bookmark() {
                Note = reader.ReadString(),
                CreatedOn = DateTime.FromBinary(reader.ReadInt64()),
                LastModifiedOn = DateTime.FromBinary(reader.ReadInt64()),
                Selection = new DigitalQuran.Selection((QuranObjectType)reader.ReadByte(),
                    new List<int>(reader.ReadInt32()))
            };

            for (int i = b.Selection.Indexes.Capacity - 1; i >= 0; i--) {
                b.Selection.Indexes.Add(reader.ReadInt32());
            }

            return b;
        }

        internal static void SaveToStream(Bookmark b, BinaryWriter writer) {
            writer.Write(b.Note);
            writer.Write(b.CreatedOn.ToBinary());
            writer.Write(b.LastModifiedOn.ToBinary());

            writer.Write((byte)b.Selection.Scope);
            writer.Write(b.Selection.Indexes.Count);
            foreach (var index in b.Selection.Indexes) {
                writer.Write(index);
            }
        }

        #endregion IO
    }
}